package com.balance.anole.erp.accessory.model;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.eclipse.core.runtime.preferences.ConfigurationScope;
import org.osgi.service.prefs.BackingStoreException;
import org.osgi.service.prefs.Preferences;

import com.balance.anole.erp.Activator;

public abstract class PrinterConfiguration {

	private static final String PRINT_CONFIG = "PRINT_CONFIG";
	private static String printerName = "";

	static {
		Preferences preferences = new ConfigurationScope()
		.getNode(Activator.PLUGIN_ID);
		printerName = preferences.get(PRINT_CONFIG, "");
	}


	public static void setPrinterName(String name) {
		Preferences preferences = new ConfigurationScope()
				.getNode(Activator.PLUGIN_ID);
		preferences.put(PRINT_CONFIG, name);
		try {
			preferences.flush();
		} catch (BackingStoreException e) {
			e.printStackTrace();
		}
		printerName = name;
	}

	public static String getPrinterName() {
		return printerName;
	}

	public static PrintService getDefaultPrinter(){
		PrintService selectedPrint = null;
		PrintService[] services = PrintServiceLookup.lookupPrintServices(
				null, null);
		for (int i = 0; i < services.length; i++) {
			if (services[i].getName().toUpperCase().contains(
					printerName.toUpperCase())) {
				/*
				 * If the service is named as what we are querying we select
				 * it
				 */
				selectedPrint = services[i];
			}
		}
		return selectedPrint;
	}

}
